package com.rxt.thermopro.ui.fragment

import android.app.Dialog
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.ProgressBar
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.widget.PressImageView
import com.rxt.ble.BleManager
import com.rxt.ble.callback.BleScanCallback
import com.rxt.ble.data.BleDevice
import com.rxt.ble.data.BleScanState
import com.rxt.ble.scan.BleScanRuleConfig
import com.rxt.thermopro.R
import com.rxt.thermopro.adapter.BluetoothAdapter
import com.rxt.thermopro.bean.BluetoothBean
import kotlinx.android.synthetic.main.dialog_bluetooth_list.*
import kotlinx.coroutines.*

class BluetoothListDialog : DialogFragment() {

    private val job = Job()
    private val mainScope = CoroutineScope(Dispatchers.Main + job)

    private lateinit var contentView: View
    private var isShow = false
    private var mScreenDensity = 0f
    private var mScreenHeight = 0
    private var mScreenWidth = 0
    private lateinit var adapter: BluetoothAdapter
    private lateinit var recyclerDevice: RecyclerView
    private lateinit var loadingView: ProgressBar
    private lateinit var cancelView: PressImageView
    private val bluetoothList = mutableListOf<BluetoothBean>()
    private var mListener: OnDialogBluetoothListener? = null

    interface OnDialogBluetoothListener {
        fun onItemClick(name: String?, address: String, bleDevice: BleDevice?)
        fun onCancel()
    }

    fun setOnDialogBluetoothListener(listener: OnDialogBluetoothListener) {
        mListener = listener
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireActivity())

        contentView = View.inflate(requireContext(), R.layout.dialog_bluetooth_list, null)
        initListener()

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(contentView)
        dialog.setCanceledOnTouchOutside(true)

        val displayMetrics = DisplayMetrics()
        requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
        mScreenDensity = displayMetrics.density
        mScreenHeight = displayMetrics.heightPixels
        mScreenWidth = displayMetrics.widthPixels

        isCancelable = false
        val window: Window? = dialog.window
        if (window != null) {
            window.setBackgroundDrawable(ColorDrawable(resources.getColor(android.R.color.transparent)))
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            val lp: WindowManager.LayoutParams = window.attributes
            lp.gravity = Gravity.CENTER
            lp.width = mScreenWidth * 4 / 5
            lp.height = mScreenHeight * 2 / 3
            window.attributes = lp
        }

        return dialog
    }

    private fun initListener() {
        adapter = BluetoothAdapter(bluetoothList)
        loadingView = contentView.findViewById(R.id.loadingView)
        recyclerDevice = contentView.findViewById(R.id.recyclerDevice)
        cancelView = contentView.findViewById(R.id.cancelView)
        recyclerDevice.layoutManager = LinearLayoutManager(context)
        recyclerDevice.adapter = adapter

        cancelView.setOnClickListener {
            mListener?.onCancel()
            hideDialog()
        }

        adapter.setOnItemClick(object : BluetoothAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                BleManager.getInstance().cancelScan()
                mListener?.onItemClick(
                    adapter.list[position].name,
                    adapter.list[position].address,
                    adapter.list[position].bleDevice
                )
                hideDialog()
            }
        })
    }

    fun showDialog(fragmentManager: FragmentManager) {
        try {
            if (!isShow) {
                this.show(fragmentManager, "TAG")
                isShow = true
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("123->", "showDialog Exception $e")
        }

    }

    fun hideDialog() {
        if (isShow) {
            dismiss()
            isShow = false
        }
    }

    override fun dismiss() {
        super.dismiss()
        BleManager.getInstance().cancelScan()
    }

    override fun onResume() {
        super.onResume()
        isShow = true
    }

    override fun onPause() {
        super.onPause()
        isShow = false
    }

    override fun show(manager: FragmentManager, tag: String?) {
        val ft = manager.beginTransaction()
        ft.add(this, tag)
        ft.commitAllowingStateLoss()
        searchBluetooth()
    }

    private val handler = Handler(Looper.getMainLooper())

    /**
     * 扫描蓝牙
     */
    private fun searchBluetooth() {
        Log.d("123->", "BluetoothListDialog searchBluetooth")
        mainScope.launch {
            delay(1000)
            var hasScanResult = false
            while (BleManager.getInstance().scanSate != BleScanState.STATE_IDLE) {
                Log.d("123->", "BluetoothListDialog 还未停止扫描")
                if (BleManager.getInstance().scanSate == BleScanState.STATE_SCANNING) {
                    BleManager.getInstance().cancelScan()
                }
                delay(500)
            }

            val scanRuleConfig = BleScanRuleConfig.Builder()
//            .setServiceUuids(serviceUuids) // 只扫描指定的服务的设备，可选
//            .setDeviceName(true, names) // 只扫描指定广播名的设备，可选
//            .setDeviceMac(mac) // 只扫描指定mac的设备，可选
                .setAutoConnect(false) // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(0) // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build()

            BleManager.getInstance().initScanRule(scanRuleConfig)
            BleManager.getInstance().scan(object : BleScanCallback() {
                override fun onScanStarted(success: Boolean) {
                    // 开始扫描（主线程）
//                    loadingView.visibility = View.VISIBLE
                    Log.d("123->", "BluetoothListDialog onScanStarted success=$success")

                    handler.postDelayed({
                        if (!hasScanResult) {
                            searchBluetooth()
                        }
                    }, 3000)
                }

                override fun onScanning(bleDevice: BleDevice?) {
                    // 扫描到一个符合扫描规则的BLE设备（主线程）
                    Log.d("123->", bleDevice?.name + "\n" + bleDevice?.mac + "\n" + bleDevice?.rssi)
                    hasScanResult = true
                    if ((bleDevice?.name ?: "").isNotEmpty()) {
//                        loadingView.visibility = View.GONE
                        val deviceIcon = when {
                            bleDevice?.name?.contains("tp25", true) == true -> {
                                R.mipmap.tp_25
                            }
                            bleDevice?.name?.contains("tp920", true) == true ||
                                    bleDevice?.name?.contains("grill", true) == true -> {
                                R.mipmap.tp_920
                            }
                            bleDevice?.name?.contains("tp930", true) == true ||
                                    bleDevice?.name?.contains("bbq", true) == true -> {
                                R.mipmap.tp_930
                            }
                            bleDevice?.name?.contains("tp960r", true) == true -> {
                                R.mipmap.tp960
                            }
                            bleDevice?.name?.contains("tp359", true) == true -> {
                                R.mipmap.tp_359
                            }
                            else -> -1
                        }
                        if (!adapter.hasBlueDevice(bleDevice?.mac) && deviceIcon != -1) {
                            val listSize = adapter.list.filter { it.deviceIcon == deviceIcon}.size
                            val newName=if (listSize>0) bleDevice?.name+"(${listSize})" else bleDevice?.name
                            adapter.add(
                                BluetoothBean(
                                    newName,
                                    bleDevice?.mac ?: "",
                                    deviceIcon,
                                    bleDevice
                                )
                            )
                        }
                    }
//                adapter?.add(BluetoothBean(bleDevice?.name, bleDevice?.mac ?: ""))
                }

                override fun onScanFinished(scanResultList: List<BleDevice?>?) {
                    // 扫描结束，列出所有扫描到的符合扫描规则的BLE设备（主线程）
                    Log.d("123->", "scanResultList=$scanResultList")
                    hasScanResult = true
                    handler.removeCallbacksAndMessages(null)
                }
            })
        }
    }

}